package com.simplegui.examples.ricerocks;

import java.util.ArrayList;
import java.util.List;

import com.simplegui.api.Canvas;
import com.simplegui.api.Frame;
import com.simplegui.api.Game;
import com.simplegui.api.GameComponent;
import com.simplegui.api.handlers.DrawHandler;
import com.simplegui.api.handlers.KeyDownHandler;
import com.simplegui.api.handlers.KeyUpHandler;
import com.simplegui.api.util.Key;

public class RiceRocks extends Game {

	
	public static int score = 0;
	public static int lives = 3;
	public static double time = 0.5;
	
	private boolean started;
	private Ship ship;
	private DrawHandler drawHandler;
	private KeyDownHandler keyDownHandler;
	private KeyUpHandler keyUpHandler;
	
	private List<GameComponent> extraGameComponents;
	
	public RiceRocks() {
		started = true;
		
		ship = new Ship(this, new Double[]{50d,50d}, false, 0, 0);
		addGameComponent(ship);
		
		drawHandler = new DrawHandler() {
			
			@Override
			public void draw(Canvas canvas) {
				executeLogic();
				ship.draw(canvas);
				
				List<GameComponent> deadComponents = new ArrayList<>();
				for (GameComponent gameComponent : extraGameComponents) {
					gameComponent.draw(canvas);
					Sprite sprite = (Sprite)gameComponent;
					if (!sprite.isAlive()){
						deadComponents.add(sprite);
					}
				}
				
				for (GameComponent gameComponent : deadComponents) {
					removeExtraGameComponent(gameComponent);
				}
				
			}
		};
		
		keyDownHandler = new KeyDownHandler() {
			@Override
			public void onKeyDown(Key key) {
				if (started){
					if (Key.LEFT == key){
						ship.decrementAngleVel();
					}else if (Key.RIGHT == key){
						ship.incrementAngleVel();
				    }else if (Key.UP == key){
				    	ship.setThrust(true);
				    }else if (Key.SPACE == key){
				    	ship.shoot();
				    }
				}
			}
		};
		
		keyUpHandler = new KeyUpHandler() {
			
			@Override
			public void onKeyUp(Key key) {
				if (started){
					if (Key.LEFT == key){
						ship.incrementAngleVel();
					}else if (Key.RIGHT == key){
						ship.decrementAngleVel();
				    }else if (Key.UP == key){
				    	ship.setThrust(false);
				    }
				}
			}
		};
		
		extraGameComponents = new ArrayList<>();
		
	}
	
	@Override
	public void configureFrame(Frame frame) {
		frame.setDrawHandler(drawHandler);
		frame.setKeyDownHandler(keyDownHandler);
		frame.setKeyUpHandler(keyUpHandler);
	}

	public boolean addExtraGameComponent(GameComponent gameComponent) {
		extraGameComponents.add(gameComponent);
		return super.addGameComponent(gameComponent);
	}
	
	public void removeExtraGameComponent(GameComponent gameComponent) {
		extraGameComponents.remove(gameComponent);
		super.removeGameComponent(gameComponent);
	}

}
